package com.ittsang.controller;

import cn.hutool.core.util.StrUtil;
import com.ittsang.dto.R;
import com.ittsang.utils.SystemConstants;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @javax.annotation.Resource
    private SystemConstants systemConstants;

    /**
     *  上传图片接口
     * @param image
     * @return
     */
    @PostMapping("/image")
    public R uploadImage(@RequestParam("multipartFile") MultipartFile image) {
        try {
            // 获取原始文件名称
            String originalFilename = image.getOriginalFilename();
            // 生成新文件名
            String fileName = createNewFileName(originalFilename);
            // 保存文件
            image.transferTo(new File(systemConstants.getIMAGE_UPLOAD_DIR(), fileName));
            // 返回结果
            return R.ok("上传成功").put("photo", "http://localhost:8090/image" + fileName);
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败", e);
        }
    }

    private String createNewFileName(String originalFilename) throws IOException{

        Resource resource = new ClassPathResource("image/1.txt");
        String path = resource.getFile().getPath();
        {
            try {
                path = resource.getFile().getPath();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String newPath = path.replace("1.txt", "");
        systemConstants.setIMAGE_UPLOAD_DIR(newPath);

        // 获取后缀
        String suffix = StrUtil.subAfter(originalFilename, ".", true);
        // 生成目录
        String name = UUID.randomUUID().toString();
        int hash = name.hashCode();
        int d1 = hash & 0xF;
        int d2 = (hash >> 4) & 0xF;
        // 判断目录是否存在
        File dir = new File(systemConstants.getIMAGE_UPLOAD_DIR(), StrUtil.format("/ittsang/{}/{}", d1, d2));
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // 生成文件名
        return StrUtil.format("/ittsang/{}/{}/{}.{}", d1, d2, name, suffix);
    }
}
